package com.ibm.spatiotemp.test.query;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

import com.ibm.spatiotemp.datamodel.config.CacheServerManager;
import com.ibm.spatiotemp.datamodel.datatype.TemporalLineString;
import com.ibm.spatiotemp.datamodel.result.SpatioObjectResultSet;
import com.ibm.spatiotemp.processor.RtreeSearcher2;
import com.ibm.spatiotemp.server.config.LocalConfig;

import edu.umn.cs.spatialHadoop.core.Point;
import edu.umn.cs.spatialHadoop.core.Rectangle;

public class RtreeSearcherTestRedis {

	public static Logger logger = Logger
			.getLogger(RtreeSearcherTestRedis.class);

	String r_tree_path;
	RtreeSearcher2<TemporalLineString> r_searcher_redis_nocache;
	Rectangle query_rec;
	Point query_point;

	@Before
	public void setUp() throws Exception {

		CacheServerManager.init("conf/redisservers.conf");

		// linestring R-tree index path
		r_tree_path = "test_index/data_00001.rtree";
		query_rec = new Rectangle(380, 430, 400, 450);
		query_point = new Point(0, 500);

		/**
		 * during test case, mammually upload it into memcache redis, currently,
		 * redis cache support ttl expiration polocy, so , not need to load
		 * index to cache mammually
		 */
		/*
		 * IndexDataLoader loader =
		 * IndexDataLoaderFactory.getIndexDataLoaderInstance(r_tree_path);
		 * loader.uploadIndexByPathKey(r_tree_path, false); loader.close();
		 * logger.info("index data uploaded to redis");
		 */

		/**
		 * true=load2cache means first find this path, load the data to redis,
		 * Notice that, data will expired in Localconfig.CacheExtireTime seconds
		 */
		if (r_searcher_redis_nocache == null)
			r_searcher_redis_nocache = new RtreeSearcher2<TemporalLineString>(
					r_tree_path, new TemporalLineString(), LocalConfig.NeedLoadToCache);
	}

	@Test
	public void Range_Query_MemBased() {
		try {
			int cnt = 0;
			SpatioObjectResultSet rset = r_searcher_redis_nocache
					.Range_Query(query_rec);

			while (rset.next()) {
				Object obj = rset.getObject(0);
				System.out.println(obj);
				++cnt;
			}

			rset.close();
			System.out.println("total result size: " + cnt);
		} catch (Exception e) {
			logger.error(e);
		}

	}

	@Test
	public void KNN_Query_MemBased() {
		try {
			int cnt = 0;
			SpatioObjectResultSet rset = r_searcher_redis_nocache.KNN_Query(
					query_point, 1);
			while (rset.next()) {
				Object obj = rset.getObject(0);
				System.out.println(obj);
				++cnt;
			}

			rset.close();
			System.out.println("total result size: " + cnt);
		} catch (Exception e) {
			logger.error(e);
		}

	}

}
